package cn.dgut.training.service.impl;

import cn.dgut.training.entity.Permission;
import cn.dgut.training.mapper.PermissionMapper;
import cn.dgut.training.service.IPermissionService;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    @Resource
    private PermissionMapper permissionMapper;



    public Set<String> queryByRoleIds(Integer[] roleIds) {

            Set<String> permissions = new HashSet<String>();
            if(roleIds.length == 0){
                return permissions;
            }
            List<Permission> permissionList = new ArrayList<>();
            for(Integer id:roleIds) {
                QueryWrapper queryWrapper =new QueryWrapper();
                if(id!=null)
                queryWrapper.eq("role_id", id);
                List<Permission> permissions1 = permissionMapper.selectList(queryWrapper);
                permissionList.addAll(permissions1);
            }

            for(Permission permission : permissionList){
                permissions.add(permission.getPermission());
            }

            return permissions;

        }

    public boolean checkSuperPermission(Integer roleId) {
        QueryWrapper queryWrapper=new QueryWrapper();
        if(roleId!=null)
            queryWrapper.eq("role_id",roleId);
            queryWrapper.eq("permission","*");
            queryWrapper.eq("deleted",false);

        List<Permission> Permissions=permissionMapper.selectList(queryWrapper);

        return Permissions.size()!=0;
    }

    public void add(Permission permission) {
        permission.setAddTime(DateTime.now());
        permission.setUpdateTime(DateTime.now());
        permissionMapper.insert(permission);
    }

    public Set<String> queryByRoleId(Integer roleId) {
        Set<String> permissions = new HashSet<String>();
        if(roleId == null){
            return permissions;
        }

        QueryWrapper queryWrapper =new QueryWrapper();
        queryWrapper.eq("role_id", roleId);
        List<Permission> permissionList = permissionMapper.selectList(queryWrapper);

        for(Permission permission : permissionList){
            permissions.add(permission.getPermission());
        }

        return permissions;
    }
}
